<script lang="ts">
  import { create as create_board } from "$lib/api/board/board";
  import { join as join_board } from "$lib/api/board/board_member";
  import { userStore } from "$lib/stores/user.svelte";
  import { request } from "$lib/utils/request";
  import { Modal, Tabs } from "@skeletonlabs/skeleton-svelte";
  import type { Store as ToastStore } from "@zag-js/toast";
  import { X } from "lucide-svelte";
  import { getContext } from "svelte";

  const toast: ToastStore = getContext("toast");

  interface ModalProps {
    onClose: () => void;
  }
  let props: ModalProps = $props();

  let curTab = $state("create");
  let boardName = $state("");
  let inviteMsg = $state("");

  const inviteCode = $derived(() => {
    const matches = inviteMsg.match(/([a-zA-Z0-9]{64})/);
    if(matches == null){
      return "";
    }
    if(matches.length > 0 && matches[0].length == 64){
      return matches[0];
    }
    return "";
  });

  const valid = $derived(() => {
    if (curTab == "create") {
      return boardName.trim() != "";
    } else {
      return inviteCode() != "";
    }
  });

  async function createBoard() {
    await request(
      create_board({
        session_id: userStore.userSession,
        basic_info: {
          board_name: boardName.trim(),
        },
      }),
    );
    toast.create({
      title: "成功",
      description: "创建频道成功!",
      type: "success",
    });
    props.onClose();
  }

  async function joinBoard() {
    await request(
      join_board({
        session_id: userStore.userSession,
        invite_code: inviteCode().trim(),
      }),
    );
    toast.create({
      title: "成功",
      description: "加入频道成功！",
      type: "success",
    });
    props.onClose();
  }
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
  backdropClasses="backdrop-blur-xs"
  backdropBase="backdrop-none"
  onOpenChange={(ev) => {
    if (!ev.open) {
      props.onClose();
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">创建/加入频道</h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => props.onClose()}
      >
        <X />
      </button>
    </header>

    <Tabs
      value={curTab}
      onValueChange={(e) => (curTab = e.value)}
      listMargin="mb-0"
    >
      {#snippet list()}
        <Tabs.Control value="create">创建</Tabs.Control>
        <Tabs.Control value="join">加入</Tabs.Control>
      {/snippet}
      {#snippet content()}
        <Tabs.Panel value="create" classes="overflow-y-auto pt-2">
          <label class="label relative p-2">
            <span class="label-text">名称</span>
            <input
              class="input rounded-none bg-surface-100-900 text-surface-900-100"
              type="text"
              placeholder="请输入频道名称"
              bind:value={boardName}
            />
          </label>
        </Tabs.Panel>
        <Tabs.Panel value="join" classes="overflow-y-auto pt-2">
          <div class="label p-2">
            <textarea
              class="textarea rounded-none bg-surface-100-900 text-surface-900-100"
              rows="2"
              placeholder="请输入邀请信息"
              bind:value={inviteMsg}
            ></textarea>
          </div>
        </Tabs.Panel>
      {/snippet}
    </Tabs>

    <footer class="flex justify-end gap-4">
      <button
        type="button"
        class="btn preset-tonal"
        onclick={() => props.onClose()}>取消</button
      >
      <button
        type="button"
        class="btn preset-filled-primary-900-100"
        disabled={!valid()}
        onclick={() => {
          if (curTab == "create") {
            createBoard();
          } else {
            joinBoard();
          }
        }}
      >
        {curTab == "create" ? "创建" : "加入"}
      </button>
    </footer>
  {/snippet}
</Modal>
